package cn.thoughtworks.school.programCenter.services;

import cn.thoughtworks.school.programCenter.entities.Follow;
import cn.thoughtworks.school.programCenter.entities.Task;
import cn.thoughtworks.school.programCenter.feign.VisualizationCenterFeign;
import cn.thoughtworks.school.programCenter.repositories.FollowRepository;
import cn.thoughtworks.school.programCenter.repositories.ReviewQuizRepository;
import cn.thoughtworks.school.programCenter.repositories.TaskRepository;
import cn.thoughtworks.school.programCenter.util.excel.AssignmentStatusExcel;
import cn.thoughtworks.school.programCenter.util.excel.BasicQuizOverviewExcel;
import cn.thoughtworks.school.programCenter.util.excel.Excel;
import cn.thoughtworks.school.programCenter.util.excel.SumPointExcel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MyStudentsService {
    @Autowired
    private FollowRepository followRepository;
    @Autowired
    private UserCenterService userCenterService;
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private ReviewQuizRepository reviewQuizRepository;
    @Autowired
    private VisualizationCenterFeign visualizationCenterFeign;

    public void getMyStudentsSumPointExportExcel(Long userId, Long programId, HttpServletResponse response) throws IOException {
        String fileName = "学员积分榜";
        List<Follow> myFollowStudents = followRepository.findByProgramIdAndTutorId(programId, userId);
        List<Map> currentProgramFollowStudents = getCurrentProgramFollowStudents(myFollowStudents);
        List<Map<String, String>> studentsSumPoint = currentProgramFollowStudents.stream().map(student -> {
            Map<String, String> studentGrade = new HashMap();
            Long id = Long.parseLong(student.get("id").toString());
            Integer sumGrade = getAllTaskGrade(programId, id);
            studentGrade.put("name", getUserName(student));
            studentGrade.put("sumPoint", sumGrade.toString());
            return studentGrade;
        }).collect(Collectors.toList());

        Excel sumPointExcel = SumPointExcel.init(studentsSumPoint);
        HSSFWorkbook workbook = sumPointExcel.fillData();
        responseDownloadWorkbook(response, fileName, workbook);
    }

    private String getUserName(Map student) {
        return Objects.equals("", student.get("name")) ? student.get("username").toString() : student.get("name").toString();
    }


    public List<Map> getCurrentProgramFollowStudents(List<Follow> myFollowStudents) {
        String userIds = myFollowStudents.stream().map(follow -> follow.getStudentId().toString()).collect(Collectors.joining(","));
        return userCenterService.getUsersByIds(userIds);
    }

    public Integer getAllTaskGrade(Long programId, Long studentId) {
        List<Task> tasks = taskRepository.findTaskByProgramIdAndVisible(programId, true);
        if (tasks.isEmpty()) {
            return 0;
        }
        Long scores = reviewQuizRepository.getScores(studentId, getTaskIds(tasks));
        return Objects.isNull(scores) ? 0 : Integer.parseInt(scores.toString());
    }

    private List<Long> getTaskIds(List<Task> tasks) {
        return tasks.stream().map(Task::getId).collect(Collectors.toList());
    }

    public void exportProgramStudentsAssignmentStatusExcel(Long userId, String type, Long programId, HttpServletResponse response) throws IOException {
        String fileName = "Program Student Assignment Status";
        List<Map<String, String>> assignmentsStudentsStatus = visualizationCenterFeign.findAssignmentsStudentsStatus(type, programId, userId).getBody();

        Excel assignmentStatusExcel = AssignmentStatusExcel.init(assignmentsStudentsStatus);
        HSSFWorkbook workbook = assignmentStatusExcel.fillData();
        responseDownloadWorkbook(response, fileName, workbook);
    }

    private void responseDownloadWorkbook(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
        String fileNameStr = fileName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileNameStr.getBytes("gb2312"), "ISO8859-1") + "\"");

        ServletOutputStream os = response.getOutputStream();
        workbook.write(os);
        os.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        os.flush();
        os.close();
    }

    public void exportBasicQuizOverviewByAssignment(Long userId, String type, Long programId, Long assignmentId, HttpServletResponse response) throws IOException {
        String fileName = "Basic Quiz Overview";
        List<Map<String, String>> data = visualizationCenterFeign.findAssignmentsStatusByAssignment(type, 241L,7849L, 3205L).getBody();

        HSSFWorkbook workbook = BasicQuizOverviewExcel.init(data)
            .fillData();
        responseDownloadWorkbook(response, fileName, workbook);
    }
}
